package algorithm.niuke;

import java.util.ArrayList;

public class 和为S的连续序列 {
    static ArrayList<ArrayList<Integer>> result = new ArrayList<>();
    static boolean isAbleFind = true;

    public static ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        for (int i = 2; i <= sum; i++) {
            if (isAbleFind) {
                compose(sum, i);
            }else {
                break;
            }
        }
        if (!result.isEmpty()) {
            ArrayList<ArrayList<Integer>> order = new ArrayList<>();
            for (int i = result.size() - 1; i >= 0; i--) {
                order.add(result.get(i));
            }
            return order;
        }
        return result;
    }

    static void compose(int sum, int count) {
        int min = -1007;
        if (count % 2 == 1 && sum % count == 0) {
            // 15 3 = 5--0 |4 5 6
            min = sum / count - count / 2;
        } else if (count % 2 == 0 && sum % count != 0) {
            // 33 % 6 = 5 3 |3 4 5 6 7 8
            // 14 % 4 = 3 2| 2 3 4 5
            if (sum % count == count / 2) {
                min = sum / count - count / 2 + 1;
            }
        }
        if (min >= 1) {
            // 成功找到
            ArrayList<Integer> temp = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                temp.add(i + min);
            }
            result.add(temp);
        } else if (min != -1007) {
            // 可以结束查找了
            isAbleFind = false;
        }
        // 没有找到
    }

    public static void main(String[] args) {
        FindContinuousSequence(9);
    }
}
